//
//  ZCFileManager.m
//  MHK
//
//  Created by ZhangCheng on 16/7/18.
//  Copyright © 2016年 ZhangSen. All rights reserved.
//

#import "ZCFileManager.h"
#import "ZCWebServiceHelper.h"
#import "ZipArchive.h"
@interface ZCFileManager()<UIAlertViewDelegate>
{
}

@property(nonatomic, assign)BOOL isRich;

@end

@implementation ZCFileManager
+(ZCFileManager *)sharedInstance{
    static ZCFileManager *zcFileManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        zcFileManager = [[ZCFileManager alloc]init];
    });
    return zcFileManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
    }
    return self;
}
-(BOOL)existFileOfCurrentId{
    return [self existFileOfId:self.currentId];
}
-(BOOL)existFileOfId:(NSString *)stringId{
    NSFileManager *fm = [[NSFileManager alloc]init];
    return [fm fileExistsAtPath:[self directPathForFileOfId:stringId]];
}

-(BOOL)existReportFileOfPaperId:(NSString *)paperId andReportId:(NSString *)reportId{
    NSFileManager *fm = [[NSFileManager alloc]init];
    BOOL result = [fm fileExistsAtPath:[self directPathForRecordFileOfId:paperId andReportId:reportId]];
    if (result) {
        NSArray *array = [fm contentsOfDirectoryAtPath:[self directPathForRecordFileOfId:paperId andReportId:reportId] error:nil];
        result = array.count!=0;
    }
    return result;
}

-(NSString *)directPathForRecordFileOfId:(NSString *)paperId andReportId:(NSString *)reportId{
    return [[self directPathForRecordFileOfId:paperId]stringByAppendingPathComponent:reportId];
}

-(void)downloadAndUnzipFileOfId:(NSString*)stringId Andpath:(NSString*)path completionBlock:(void(^)(void))completionBlock failedBlock:(void(^)(void))failedBlock{
    //远程地址
    NSURL *URL = [NSURL URLWithString:path];
//    NSLog(@"%@",URL);
    //默认配置
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    //AFN3.0+基于封住URLSession的句柄
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    //请求
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    //下载Task操作
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        // @property int64_t totalUnitCount;     需要下载文件的总大小
        // @property int64_t completedUnitCount; 当前已经下载的大小
        // 给Progress添加监听 KVO
//        NSLog(@"%f\n%lld\n%lld",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount,downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
        // 回到主队列刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            // 设置进度条的百分比
            [self setProgress: 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount];
        });
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径
        NSString *pathString = PATH_CACHE_DIR;
        NSString *desPathString = [pathString stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:desPathString];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (!error) {
            NSString *imgFilePath = [filePath path];// 将NSURL转成NSString
            [SVProgressHUD showInfoWithStatus:@"文件解压中"];
            ZipArchive* zip = [[ZipArchive alloc] init];
            if( [zip UnzipOpenFile:imgFilePath] ){
                BOOL result = [zip UnzipFileTo:[[ZCFileManager sharedInstance] directPathForFileOfId:stringId] overWrite:YES];
                if( NO ==result ){
                    //添加代码
                    [SVProgressHUD showErrorWithStatus:@"解压文件失败"];
                }
                [zip UnzipCloseFile];
                NSFileManager *fm = [[NSFileManager alloc]init];
                [fm removeItemAtPath:imgFilePath error:nil];
                [SVProgressHUD dismiss];
                completionBlock();
                [[[NSFileManager alloc]init]removeItemAtPath:imgFilePath error:nil];
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"打开解压文件失败"];
            }
        }else{
            [SVProgressHUD showErrorWithStatus:@"下载文件失败！"];
        }
    }];
    [downloadTask resume];
}

- (BOOL)zipFilesOfArray:(NSArray *)files ofReportId:(NSString *)reportId
{
    // 1
    NSString *paths = PATH_TEMP_DIR;
    
    // 2
    NSString *zipFile = [paths stringByAppendingPathComponent:[NSString stringWithFormat:@"report%@.zip",reportId]];
    // 4
    ZipArchive *za = [[ZipArchive alloc] init];
    [za CreateZipFile2:zipFile];
    
    // 6
    for (NSString *string in files) {
        [za addFileToZip:[[[ZCPaperManager sharedInstance] currentRecordingDir] stringByAppendingPathComponent:string] newname:string];
    }
    // 7
    BOOL success = [za CloseZipFile2];
    NSLog(@"Zipped file with result %d",success);
    return success;
}

-(void)setProgress:(float)newProgress{
    [SVProgressHUD showProgress:newProgress status:@"下载资源文件"];
}

-(NSString*)directPathForFileOfId:(NSString*)stringId{
    NSString *pathString = PATH_CACHE_DIR;
    NSString *dirName = [NSString stringWithFormat:@"exam%@",stringId];
    return [pathString stringByAppendingPathComponent:dirName];
}
-(NSString*)directPathForFileOfCurrentId{
    return [self directPathForFileOfId:self.currentId];
}

-(NSString *)directPathForAudioFileOfCurrentId{
    return [self directPathForFileOfCurrentId];
}

-(NSString *)directPathForRecordFileOfCurrentId{
    return [self directPathForRecordFileOfId:self.currentId];
}

-(NSString *)directPathForRecordFileOfId:(NSString *)stringId{
    NSString *pathString = PATH_REPORT_DIR;
    NSString *dirName = [NSString stringWithFormat:@"report%@",stringId];
    return [pathString stringByAppendingPathComponent:dirName];
}

-(void)removeFileOfId:(NSString*)stringId{
    if ([self existFileOfId:stringId]) {
        NSFileManager *fm = [[NSFileManager alloc]init];
        [fm removeItemAtPath:[self directPathForFileOfId:stringId] error:nil];
    }
}


@end
